package uwosh.cs342.project1;

import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView.OnGroupClickListener;
import android.widget.Toast;

public class Project1ContactListActivity extends Activity {
	private ExpandableListAdapter listAdapter;
	private ContactsDataSource contactDatabaseHelper;
	private int groupID, childID;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        //=====================================================================================
        ArrayList<String> groupNames = new ArrayList<String>();
		ArrayList<Contact> groupContacts = new ArrayList<Contact>();
		ArrayList<ArrayList<Contact>> contacts = new ArrayList<ArrayList<Contact>>();

		
		contactDatabaseHelper = new ContactsDataSource(getApplicationContext());
		contactDatabaseHelper.open();
		
		groupNames = contactDatabaseHelper.getAllGroups();
		for (int i = 0; i < groupNames.size(); i++){
			groupContacts = contactDatabaseHelper.getAllContacts(groupNames.get(i));
			contacts.add(groupContacts);
		}
		contactDatabaseHelper.close();
		//=====================================================================================
        
        ExpandableListView groupView = (ExpandableListView)findViewById(R.id.expandableGroupList);
        
        /*	This is a listener for the child click event, which will be used to begin the Show Contact
         * 	Information activity.	*/
        groupView.setOnChildClickListener(new OnChildClickListener()
        {
            
            //@Override
            public boolean onChildClick(ExpandableListView parent, View view, int groupPosition, int childPosition, long id)
            {
            	groupID = groupPosition;
            	childID = childPosition;
            	//Toast.makeText(getBaseContext(), "Child clicked", Toast.LENGTH_LONG).show();
            	//Creating an intent to send through to activity.  This Intent stores the contact info as a 
            	//String Array in the following format(Based on D2L Document):
        		//contactInf[0] = FirstName
        		//contactInf[1] = LastName
        		//contactInf[2] = Address
        		//contactInf[3] = CellPhone
        		//contactInf[4] = HomePhone
        		//contactInf[5] = 3rd Phone
        		//contactInf[6] = Email
        		//contactInf[7] = Comments
            	//Currently this is just a static example to demonstrate since we do not have a database connection yet
                Intent i = new Intent();
                i.setClassName("uwosh.cs342.project1", "uwosh.cs342.project1.ContactInfoActivity");
                i.putExtra("uwosh.cs342.project1.groupID", groupPosition);
                i.putExtra("uwosh.cs342.project1.childID", childPosition);
                i.putExtra("uwosh.cs342.project1.groups", listAdapter.getAllGroups());
                /*i.putExtra("Example", new String[] { "Trevor", "Klapper", "w1253 Main Street", "414-411-4611",
    					"920-444-1112", "951-512-2111", "klappt98@uwosh.edu", "This dude is awesome! (Comment Section Test)"});*/
                Contact selectedContact = (Contact)listAdapter.getChild(groupPosition, childPosition);
                String[] contactInfo = {selectedContact.getContactFirstName(), selectedContact.getContactLastName(),
                		selectedContact.getContactAddress(), selectedContact.getContactCellPhone(), selectedContact.getContactHomePhone(),
                		selectedContact.getContactAltPhone(), selectedContact.getContactEmail(), selectedContact.getContactComments()};
                i.putExtra("uwosh.cs342.project1.contactInfo", contactInfo);
                startActivityForResult(i, 1000);

            	
            	return false; 
            }
            
        });//end setOnChildClickListener
        
        /*	This is a listener for the group click event, which will display a message to indicate
         * 	a group has been expanded/collapsed.	*/
        groupView.setOnGroupClickListener(new OnGroupClickListener()
        {
            
            //@Override
            public boolean onGroupClick(ExpandableListView parent, View view, int groupPosition, long id)
            {
                return false;
            }
        });//end setOnGroupClickListener
        
        groupView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener(){
        	 	    	
        	 	    	
        	 	    	public boolean onItemLongClick(AdapterView<?> parent, View v, int position, final long id)
        	 	        {	//Check to see if deleting a USER
        	 	    		 if (ExpandableListView.getPackedPositionType(id) == ExpandableListView.PACKED_POSITION_TYPE_CHILD) {
        	 	    			 //Store info on which user is being deleted
        	 		                int groupPosition = ExpandableListView.getPackedPositionGroup(id);
        	 		                int childPosition = ExpandableListView.getPackedPositionChild(id);
        	 
        	 
        	 		                //Create Confirmation Dialog for deletion
        	 		              	AlertDialog.Builder  delAlert  = new AlertDialog.Builder(v.getContext());
        	 		              	final Contact deleteing = (Contact) listAdapter.getChild(groupPosition, childPosition);
        	 		    		    delAlert.setMessage("Are you sure you want to delete " + listAdapter.getChild(groupPosition, childPosition).toString());
        	 		    		    delAlert.setCancelable(true);
        	 		    		    delAlert.setPositiveButton("Ok",
        	 		    		    		new DialogInterface.OnClickListener() {
        	     		    	        public void onClick(DialogInterface dialog, int which) {
        	     		    	        	contactDatabaseHelper.open();
        	     		    	        	contactDatabaseHelper.deleteContact(deleteing);
        	     		    	        	contactDatabaseHelper.close();
        	     		    	        	Toast.makeText(getBaseContext(), "Deleted", Toast.LENGTH_LONG).show();
        	     		    	        	
        	     		    	        	int groupPosition = ExpandableListView.getPackedPositionGroup(id);
                	 		                int childPosition = ExpandableListView.getPackedPositionChild(id);
        	     		    	        	listAdapter.deleteContact(groupPosition, childPosition);
        	     		    	        	handler.sendEmptyMessage(1);
        	     		    	        }
        	     		    	    });
        	 		    		    //If user cancels delete, just close dialog
        	 		    		    delAlert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        	     		    	        public void onClick(DialogInterface dialog, int which) {
        	 	    		    	          dialog.dismiss();
        	 	    		    	        }
        	 	    		    	    });		    		    
        	 		                
        	 		    		   delAlert.create().show();
        	 		                return true;
        	 		            }
        	 	    		 //If Deleting a Group:
        	 	    		 if (ExpandableListView.getPackedPositionType(id) == ExpandableListView.PACKED_POSITION_TYPE_GROUP) {
        	 		                int groupPosition = ExpandableListView.getPackedPositionGroup(id);
        	 		                
        	 		                //Show Dialog for deleting a Group
        	 		                final String groupName = listAdapter.getGroupName(groupID);
        	 		                
        	 		              	AlertDialog.Builder  delAlert  = new AlertDialog.Builder(v.getContext());
        	 		    		    delAlert.setMessage("Are you sure you want to delete " + listAdapter.getGroup(groupPosition).toString());
        	 		    		    delAlert.setCancelable(true);
        	 		    		    delAlert.setPositiveButton("Ok",
        	 		    		    		new DialogInterface.OnClickListener() {
        	     		    	        public void onClick(DialogInterface dialog, int which) {
        	     		    	        	contactDatabaseHelper.open();
        	     		    	        	contactDatabaseHelper.deleteGroup(groupName);
        	     		    	        	contactDatabaseHelper.close();
        	     		    	        	Toast.makeText(getBaseContext(), "Deleted", Toast.LENGTH_LONG).show();
        	     		    	        	
        	     		    	        	int groupPosition = ExpandableListView.getPackedPositionGroup(id);
        	     		    	        	listAdapter.deleteGroup(groupPosition);
        	     		    	        	handler.sendEmptyMessage(1);
        	     		    	        }
        	     		    	    });
        	 		    		    delAlert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        	     		    	        public void onClick(DialogInterface dialog, int which) {
        	 	    		    	          dialog.dismiss();
        	 	    		    	        }
        	 	    		    	    });		    		    
        	 		                
        	 		    		   delAlert.create().show();
        	 		                return true;
        	 		            }
        	 
        	 
        	 
        	 
        	 		            return false;
        	 	        }
        	 	    	
        	 	    });
        
        //Create and set the list adapter
        listAdapter = new ExpandableListAdapter(this, groupNames, contacts);
        groupView.setAdapter(listAdapter);
        
        //Create default groups and contacts
        listAdapter.addGroup("General Contacts");
        
    }//end onCreate
    
    private Handler handler = new Handler(){
    	@Override
    	public void handleMessage(Message msg){
    		listAdapter.notifyDataSetChanged();
    		super.handleMessage(msg);
    	}
    };//end Handler
    
    /*	The addNewGroup method is a listener for the "Add Group" button. It is
     * 	responsible for starting the Add Group activity where the user enters
     * 	the name of the group to be added to the contact list.
     * 
     * 	For the request code I used a 4 digit number starting with 1, since all
     * 	the single digits already refer to pre-existing constant values.	*/
    public void addNewGroup(View view){
    	Intent myIntent = new Intent(view.getContext(), AddGroupActivity.class);
    	startActivityForResult(myIntent, 1000);
    }//end addNewGroup
    
    /*	The addNewContact method is a listener for the "Add Contact" button.
     * 	It is responsible for starting the Add Contact activity where the user
     * 	enters the contact's information and adds the contact to the contact list.
     * 
     * 	For the request code I used a 4 digit number starting with 1 and ending
     * 	with 1 to avoid getting confused with existing request codes.	*/
    public void addNewContact(View view){
    	Intent myIntent = new Intent(view.getContext(), AddContactActivity.class);
    	myIntent.putExtra("uwosh.cs342.project1.groups", listAdapter.getAllGroups());
    	myIntent.putExtra("uwosh.cs342.project1.requestCode", 1001);
    	startActivityForResult(myIntent, 1001);
    }//end addNewContact
    
    /*	The onActivityResult method is a listener that acts as a catchall for any completed
     * 	activity. For now I use the result code to determine which activity has been completed,
     * 	and how to deal with the specific activity's completion.	*/
    public void onActivityResult(int requestCode, int resultCode, Intent intent){
    	if (resultCode == 6000){
    		completeAddGroup(intent);
    	}
    	else if (resultCode == 6001){
    		completeAddContact(intent);
    	}
    	else if (resultCode == 6003){
    		Bundle extras = intent.getExtras();
    		String firstName = extras.getString("uwosh.cs342.project1.firstName");
    		String lastName = extras.getString("uwosh.cs342.project1.lastName");
	    	String email = extras.getString("uwosh.cs342.project1.email");
	    	String cellPhone = extras.getString("uwosh.cs342.project1.cellPhone");
	    	String homePhone = extras.getString("uwosh.cs342.project1.homePhone");
	    	String altPhone = extras.getString("uwosh.cs342.project1.altPhone");
	    	String comments = extras.getString("uwosh.cs342.project1.comments");
	    	String address = extras.getString("uwosh.cs342.project1.address");
    		int groupID = extras.getInt("uwosh.cs342.project1.groupID");
    		int childID = extras.getInt("uwosh.cs342.project1.childID");
    		
    		Contact updatedContact = new Contact(firstName);
    		updatedContact.setContactLastName(lastName);
			updatedContact.setContactEmail(email);
			updatedContact.setContactCellPhone(cellPhone);
			updatedContact.setContactHomePhone(homePhone);
			updatedContact.setContactAltPhone(altPhone);
			updatedContact.setContactComments(comments);
			updatedContact.setContactAddress(address);
    		listAdapter.editContact(updatedContact, this.groupID, this.childID);
    		
    		contactDatabaseHelper.open();
    		contactDatabaseHelper.editContact(updatedContact, listAdapter.getGroupName(groupID));
    		contactDatabaseHelper.close();
    		
    		handler.sendEmptyMessage(1);
    	}
    }//end onActivityResult
    
    public void completeAddGroup(Intent results){
    	Bundle extras = results.getExtras();
		if(extras != null){
			String newGroupName = extras.getString("uwosh.cs342.project1.groupName");
			listAdapter.addGroup(newGroupName);
			contactDatabaseHelper.open();
			contactDatabaseHelper.createGroup(newGroupName);
			contactDatabaseHelper.close();
			handler.sendEmptyMessage(1);
			String toastMessage = "\"" + newGroupName + "\" added to Group list.";
			Toast.makeText(getBaseContext(), toastMessage, Toast.LENGTH_LONG).show();
		}
    }//end completeAddGroup
    
    public void completeAddContact(Intent results){
    	Bundle extras = results.getExtras();
		if(extras != null){
			String firstName = extras.getString("uwosh.cs342.project1.firstName");
			String lastName = extras.getString("uwosh.cs342.project1.lastName");
	    	String email = extras.getString("uwosh.cs342.project1.email");
	    	String cellPhone = extras.getString("uwosh.cs342.project1.cellPhone");
	    	String homePhone = extras.getString("uwosh.cs342.project1.homePhone");
	    	String altPhone = extras.getString("uwosh.cs342.project1.altPhone");
	    	String comments = extras.getString("uwosh.cs342.project1.comments");
	    	String address = extras.getString("uwosh.cs342.project1.address");
			int groupPosition = extras.getInt("uwosh.cs342.project1.groupId");
			
			Contact newContact = new Contact(firstName);
			newContact.setContactLastName(lastName);
			newContact.setContactEmail(email);
			newContact.setContactCellPhone(cellPhone);
			newContact.setContactHomePhone(homePhone);
			newContact.setContactAltPhone(altPhone);
			newContact.setContactComments(comments);
			newContact.setContactAddress(address);
			
			contactDatabaseHelper.open();
			newContact = contactDatabaseHelper.createContact(newContact,listAdapter.getGroupName(groupPosition));
			contactDatabaseHelper.close();
			
			listAdapter.addContact(groupPosition, newContact);
			
			
			handler.sendEmptyMessage(1);
			String toastMessage = "\"" + firstName + "\" added to " + listAdapter.getGroup(groupPosition);
			Toast.makeText(getBaseContext(), toastMessage, Toast.LENGTH_LONG).show();
		}
    }//end completeAddContact
    
    
}//end class